import React, { useState, forwardRef, useImperativeHandle, useEffect } from 'react';
import { Button, Modal, Form, message, Input, Select, Space } from 'antd';
import { useUnitContext } from '../UnitContext';

interface AddUnitDialogProps {
  data?: { current: any };
  ref: any;
}

const FormModal: React.FC<AddUnitDialogProps> = forwardRef(({ data }, ref: any) => {
  const { addTableListItem, editTableItem } = useUnitContext();
  useImperativeHandle(ref, () => ({
    setOpen
  }));

  console.log('子组件props', data.current);
  const [open, setOpen] = useState(false);
  const [form] = Form.useForm();

  useEffect(() => {
    const { current } = data;
    if (Object.keys(current).length) {
      form.setFieldsValue(current);
    } else {
      form.resetFields();
      form.setFieldsValue({
        businessType: 1
      });
    }
  }, [open]);

  const getFormData = async () => {
    const formData = form.getFieldsValue();
    const { current } = data;
    if (Object.keys(current).length) {
      formData.id = data.current.id;
      await editTableItem(formData);
      message.success('编辑成功');
      setOpen(false);
    } else {
      await addTableListItem({ ...formData, fondsId: 5, archiveTypeId: 16 });
      message.success('提交成功');
      setOpen(false);
    }
  };

  return (
    <>
      <Modal
        title="创建批次"
        visible={open}
        footer={[
          <Button key="cancel" onClick={() => setOpen(false)}>
            关闭
          </Button>,
          <Button key="submit" type="primary" onClick={getFormData}>
            提交
          </Button>
        ]}
      >
        <Form form={form} labelCol={{ span: 6 }}>
          <Form.Item name="name" label="批次名称">
            <Input placeholder="请输入名称" />
          </Form.Item>
          <Form.Item name="businessType" label="导入方式">
            <Select disabled options={[{ value: 1, label: '离线发布' }]} />
          </Form.Item>
          <Form.Item label="选择档案库">
            <Space wrap>
              <Form.Item name="receiveMode" noStyle>
                <Select placeholder="请选择全宗" options={[{ value: 0, label: 'bar' }]} />
              </Form.Item>
              <Form.Item name="receiveType" noStyle>
                <Select placeholder="请选择" options={[{ value: 1, label: 'aaa' }]} />
              </Form.Item>
            </Space>
          </Form.Item>
          <Form.Item name="transferUnit" label="来源部门">
            <Input placeholder="请输入来源部门" />
          </Form.Item>
        </Form>
      </Modal>
    </>
  );
});

export default FormModal;
